//
//  AppDelegate.m
//  ZhiHuiLiJiang
//
//  Created by Work on 2018/11/12.
//  Copyright © 2018年 王雅鹏. All rights reserved.
//

#import "AppDelegate.h"
#import "BootPageViewController.h"//引导页VC
#import "TabBarViewController.h"//tabBarVC
#import "ZLAdvertView.h"
#import "BYSetModel.h"
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //web页cookie的处理 https://bbs.csdn.net/topics/392040635
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    [self initLoginInfoDic];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    //微信注册
    [WXApi registerApp:@"wx193c0f8b2d5197aa"];
    //极光注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            
        }else{
            
        }
    }];
    [JPUSHService setupWithOption:launchOptions appKey:@"de86c4fe8a1a3dfdd3f78c25" channel:@"AppStore" apsForProduction:YES advertisingIdentifier:nil];
    
    //引导页
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    if (![useDef boolForKey:@"notFirst"]) {// 如果是第一次进入引导页
        self.window.rootViewController = [[BootPageViewController alloc]init];
    }else{// 否则直接进入应用
        self.window.rootViewController = [[TabBarViewController alloc]init];
    }
    self.SetDataArray = [[NSMutableArray alloc]init];
    NSUserDefaults *useDefs = [NSUserDefaults standardUserDefaults];
    if ([useDefs objectForKey:@"latitude"] == nil) {
        [useDef setObject:[NSString stringWithFormat:@"%f",[@"26.86" doubleValue]] forKey:@"latitude"];
        [useDef synchronize];
    }
    
    //接口配置
    NSDictionary *dict = @{@"ver":@"1.01"};
    [BYNetworking requestGetOrPostWithType:GET url:LJURL_settings params:dict success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
        
        NSArray *dataArrs = [data objectForKey:@"data"];
        NSMutableArray *dataArrMs = [NSMutableArray arrayWithCapacity:dataArrs.count];
        for (NSDictionary *dics in dataArrs) {
            BYSetModel *topCarouselModel = [BYSetModel mj_objectWithKeyValues:dics];
            [dataArrMs addObject:topCarouselModel];
        }
        self.SetDataArray = dataArrMs.copy;
        [[NSNotificationCenter defaultCenter]postNotificationName:BYSetting object:nil];


    } fail:^(NSError * _Nonnull error) {

    } showHUD:YES];
    
//    NSDictionary *dict = @{@"ver":@"1.01"};
//    [BYNetworking requestGetOrPostWithType:GET url:LJURL_versiondesc params:@{} success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
//
//
//    } fail:^(NSError * _Nonnull error) {
//
//    } showHUD:YES];
//
//    [BYNetworking requestGetOrPostWithType:GET url:LJURL_latestversion params:@{} success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
//
//
//    } fail:^(NSError * _Nonnull error) {
//
//    } showHUD:YES];

    
    [self.window makeKeyAndVisible];
    [self setupAdvert];
    

    
    return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}


- (void)initLoginInfoDic {
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:LoginUserName];
    NSString *user_id = dict[@"user_id"];
    if (user_id == nil || user_id.length == 0) {
        [self saveLoginInfoDicWithuser_id:@"" withAccount:@"" withPhone:@"" withSission:@"" withUser_type:@"" withReg_type:@"" withStatus_type:@""];
    }else {
        //已存登陆信息,读取出来，头像使用默认头像，待登陆成功后，更新这个头像
        self.loginInfoDic = [[NSMutableDictionary alloc] init];
        [self.loginInfoDic setObject:user_id forKey:@"user_id"];
        [self.loginInfoDic setObject: dict[@"account"] forKey:@"account"];
        [self.loginInfoDic setObject: dict[@"status_type"] forKey:@"status_type"];
    }
}

//登出
- (void)logOutInfoDic {
    [self saveLoginInfoDicWithuser_id:@"" withAccount:@"" withPhone:@"" withSission:@"" withUser_type:@"" withReg_type:@"" withStatus_type:@""];
}
//保存登陆信息
- (void)saveLoginInfoDicWithuser_id:(NSString *)user_id withAccount:(NSString *)account withPhone:(NSString *)phone withSission:(NSString *)sission withUser_type:(NSString *)user_type withReg_type:(NSString *)reg_type withStatus_type:(NSString *)status_type{
    if (self.loginInfoDic == nil || self.loginInfoDic.allKeys.count == 0) {
        self.loginInfoDic = [[NSMutableDictionary alloc] init];
    }
    if (user_id != nil) {
        [self.loginInfoDic setObject:user_id forKey:@"user_id"];
        [self.loginInfoDic setObject:account forKey:@"account"];
        [self.loginInfoDic setObject:phone forKey:@"phone"];
        [self.loginInfoDic setObject:sission forKey:@"sission"];
        [self.loginInfoDic setObject:user_type forKey:@"user_type"];
        [self.loginInfoDic setObject:reg_type forKey:@"reg_type"];
        [self.loginInfoDic setObject:status_type forKey:@"status_type"];
        [[NSUserDefaults standardUserDefaults] setObject:self.loginInfoDic forKey:LoginUserName];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
/**
 *  设置启动页广告
 */
- (void)setupAdvert {
    
    // 1.判断沙盒中是否存在广告图片，如果存在，直接显示
    NSString *filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) { // 图片存在
        
        ZLAdvertView *advertView = [[ZLAdvertView alloc] initWithFrame:self.window.bounds];
        advertView.filePath = filePath;
        [advertView show];
    }
    
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [self getAdvertisingImage];
}

/**
 *  判断文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

/**
 *  初始化广告页面
 */
- (void)getAdvertisingImage {
    
//    // TODO 请求广告接口
//    // 这里原本应该采用广告接口，现在用一些固定的网络图片url代替
//    NSArray *imageArray = @[
//                            @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
//                            @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
//                            @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
//                            ];
//    NSString *imageUrl = imageArray[arc4random() % imageArray.count];
//    
//    // 获取图片名:43-130P5122Z60-50.jpg
//    NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
//    NSString *imageName = stringArr.lastObject;
//    
//    // 拼接沙盒路径
//    NSString *filePath = [self getFilePathWithImageName:imageName];
//    BOOL isExist = [self isFileExistWithFilePath:filePath];
//    if (!isExist){ // 如果该图片不存在，则删除老图片，下载新图片
//        
//        [self downloadAdImageWithUrl:imageUrl imageName:imageName];
//    }
}

/**
 *  下载新图片
 */
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名称
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [kUserDefaults setValue:imageName forKey:adImageName];
            [kUserDefaults synchronize];
            // 如果有广告链接，将广告链接也保存下来
        }else{
            NSLog(@"保存失败");
        }
        
    });
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage {
    
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  根据图片名拼接文件路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName {
    
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {//挂起、相当于进入了后台（上划进入网络控制台、来电话了）
}

- (void)applicationDidEnterBackground:(UIApplication *)application {//进入后台
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {//将要进入前台
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {//进入前台
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
     [[NSNotificationCenter defaultCenter]postNotificationName:BYEnterForeground object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {//程序即将退出
}

@end
